<script setup lang="ts">
  import { ref, unref } from 'vue'
  import { useGlobalStore } from '@/store/global'
  import IconDark from '@assets/images/headers/theme-dark.svg'
  import IconLight from '@assets/images/headers/theme-light.svg'

  const themeName = ref<AppTheme>('os-default')
  const globalStore = useGlobalStore()

  /** 跟随系统主题 */
  const themeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  themeName.value = themeMediaQuery.matches ? 'dark' : 'light'
  // 监听系统主题色变化
  themeMediaQuery.addEventListener('change', () => {
    themeName.value = themeMediaQuery.matches ? 'dark' : 'light'
    setTheme()
  })

  /**
   * 切换主题
   */
  const handleSwitchTheme = () => {
    themeName.value = unref(themeName) === 'dark' ? 'light' : 'dark'
    setTheme()
  }

  /** 设置主题 */
  const setTheme = () => {
    document.documentElement.className = unref(themeName)
    globalStore.theme = unref(themeName)
  }
  setTheme()


</script>

<template>
  <div class="theme-switch-2023" @click="handleSwitchTheme">
    <img v-if="themeName === 'dark'" class="dark" :src="IconDark" alt="dark theme icon">
    <img v-if="themeName === 'light'" class="light" :src="IconLight" alt="light theme icon">
  </div>
</template>

<style lang="scss" scoped>
  .theme-switch-2023 {
    position: relative;
    display: flex;
    align-items: center;
    width: 50px;
    height: 24px;
    background: #eee;
    border-radius: 20px;
    border: 1px solid #ccc;
    box-sizing: border-box;
    cursor: pointer;
    user-select: none;
    .dark, .light {
      position: absolute;
      width: 20px;
      height: 20px;
    }
    .dark {
      top: 1px;
      right: 5px;
    }
    .light {
      top: 2px;
      left: 5px;
    }
  }
</style>